package com.module.my.model

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.util.Pair
import android.util.Patterns
import android.webkit.URLUtil
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import com.module.app.base.BaseViewModel
import com.module.app.bean.ListViewBean
import com.module.app.bus.UpdateBus
import com.module.app.ext.updateFlow
import com.module.app.network.MyBaseResponse
import com.module.app.network.getCommonService
import com.module.app.pop.ProgressPop2
import com.module.base.ext.download
import com.module.base.ext.request
import com.module.base.utils.CommonUtils
import com.module.base.utils.DisplayUtils
import com.module.base.utils.FileCommonUtils
import com.module.base.utils.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.module.base.R
import com.module.frame.ext.postEvent
import com.module.my.adapter.holder.SkinHolder
import com.module.my.bus.SelectSkinBus
import com.module.third.learcloud.lcQuery
import com.module.third.learcloud.LCResponse
import com.module.third.learcloud.SUCCESS_CODE
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.withContext
import java.io.File


class SkinViewModel : BaseViewModel() {

    /**
     *  设置position
     */
    val positionFlow: MutableSharedFlow<Int> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    /**
     *  裁剪成功
     */
    val cropSucFlow: MutableSharedFlow<String> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    /**
     *  选中皮肤
     */
    val selectSkinFlow: MutableSharedFlow<SelectSkinBus> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }


    //主题背景的url
    private var bgUrl: String? = null


    var context: Context? = null

    var activity: Activity? = null

    fun getData() {
        request({
            val tClass = com.module.app.bean.SkinBean::class.java
            val query = LCQuery<LCObject>(tClass.simpleName)
            query.orderByAscending("sort")
            var response: LCResponse<MutableList<com.module.app.bean.SkinBean>> = lcQuery(query, tClass)
            setPosition(response.getData() ?: mutableListOf())
            return@request response
        }, {
            postEvent(listFlow,ListViewBean(true, it, true))
        }, {
            postEvent(errorFlow,it)
        }, false)
    }

    /**
     * 根据当前的皮肤，设置 setPosition
     */
    private fun setPosition(list: MutableList<com.module.app.bean.SkinBean>) {
        val cur = com.module.app.utils.MySkinUtils.getCurSkinBean()
        var curSkinName = cur?.skinName ?: ""
        for (i in list.indices) {
            val bean: com.module.app.bean.SkinBean = list[i]
            if (bean.skinName == curSkinName) {
                bean.isSelect = true
                postEvent(positionFlow,i)
                break
            }
        }
    }

    fun downloadSkin(holder: SkinHolder, bean: com.module.app.bean.SkinBean) {
        if (context == null) {
            return
        }
        XXPermissions.with(context!!)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        ProgressPop2.show(context!!, "皮肤下载")
                        val path =
                            com.module.app.utils.FileUtils.getSkinPath() + File.separator + bean.skinName + ".skin"
                        FileCommonUtils.deleteFile(path)
                        download(path, {
                            postEvent(updateFlow, UpdateBus(0f, com.module.app.bean.IType.STATUS.start))
                            //执行下载
                            getCommonService().download(bean.download)
                        }, {
                            //进度
                            postEvent(updateFlow, UpdateBus(it, com.module.app.bean.IType.STATUS.progress))
                        }, {
                            //完成
                            postEvent(updateFlow, UpdateBus(100f, com.module.app.bean.IType.STATUS.end))
                            if (!TextUtils.isEmpty(it) && it.endsWith(".skin")) {
                                postEvent(selectSkinFlow,SelectSkinBus(holder, bean))
                            } else if (TextUtils.isEmpty(it)) {
                                ToastUtils.showShortSafe("下载异常")
                            }
                        }, {
                            //失败
                            postEvent(updateFlow, UpdateBus(100f, com.module.app.bean.IType.STATUS.end))
                            ToastUtils.showShortSafe("下载异常")
                        })
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    ToastUtils.showLong(R.string.permissions_write_read_never_reject_update)
                }
            })
    }

    /**
     * 裁剪
     */
    fun crop(list: List<Any>?) {
        if (list.isNullOrEmpty()) {
            return
        }
        var isHttp = false
        request({
            //获取对应的path
            withContext(Dispatchers.IO) {
                val appBgPath = com.module.app.utils.FileUtils.getAppBgPath()
                FileCommonUtils.deleteDirectory(appBgPath, false)
                val mObject = list[0]
                var path: String? = null
                if (mObject is LocalMedia) {
                    path = mObject.realPath
                }
                check(!path.isNullOrEmpty()) {
                    "请选择图片"
                }
                //是不是网络地址
                isHttp = URLUtil.isValidUrl(path) && Patterns.WEB_URL.matcher(path).matches()
                val newPath = appBgPath + File.separator + System.currentTimeMillis()
                if (isHttp) {
                    bgUrl = path
                } else {
                    bgUrl = newPath
                    FileCommonUtils.copyFile(path, bgUrl)
                }
                return@withContext MyBaseResponse(
                    SUCCESS_CODE,
                    "",
                    Pair(path, newPath)
                )
            }
        }, {
            check(it != null) {
                CommonUtils.getString(R.string.error_unknow)
            }
            val finalPath: String = it.first
            val newFile: File = File(it.second)
            com.module.app.pop.CommonPop.Builder(context)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setContent("是否需要裁剪\n裁剪会根据当前屏幕比例裁剪")
                .setCancelButton("原图")
                .setConfirmButton("裁剪")
                .setOnCancelListener {
                    bgUrl?.let {
                        postEvent(cropSucFlow,it)
                    }
                }
                .setOnConfirmListener {
                    if (isHttp) {
                        ToastUtils.showLong("正在加载，请稍后。。。")
                    }
                    val uri =
                        if (isHttp || PictureMimeType.isContent(finalPath)) Uri.parse(
                            finalPath
                        ) else Uri.fromFile(File(finalPath))
                    val options = UCrop.Options()
                    val width = DisplayUtils.getScreenWidth(context)
                    val height =
                        DisplayUtils.getOriginalHeight(context)
                    UCrop.of(uri, Uri.fromFile(newFile))
                        .withOptions(options)
                        .withAspectRatio(1f, height.toFloat() / width)
                        .startAnimationActivity(activity!!, 0)
                }.show()
        }, {
            ToastUtils.showShort(it.msg)
        }, false)
    }

    fun getBgUrl(): String? {
        return bgUrl
    }

}